﻿/**************************************************************
 * Copyright gt1987. All rights reserved.
 * 
 * Author: guitao(guitao@eastmoney.com) 
 * Create Date: 2020/4/14 14:30:37
 * Description: MessageSendValidator
 *          
 * Revision History:
 *      Date         Author               Description
 *              
***************************************************************/

using gt.ShortMessage.Services.Validators;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace gt.ShortMessage.Services.Impls
{
    public class MessageSendValidator : IMessageSendValidator
    {
        private readonly IEnumerable<IPhoneValidator> _phoneValidators = null;
        private readonly IEnumerable<IUniqueIdValidator> _uniqueIdValidators = null;
        private readonly ILogger _logger;
        public MessageSendValidator(IEnumerable<IPhoneValidator> phoneValidators,
            IEnumerable<IUniqueIdValidator> uniqueIdValidators,
            ILogger<MessageSendValidator> logger)
        {
            _phoneValidators = phoneValidators ?? new List<IPhoneValidator>();
            _uniqueIdValidators = uniqueIdValidators ?? new List<IUniqueIdValidator>();
            _logger = logger;
        }

        public bool Validate(string phone, string uniqueId)
        {
            if (string.IsNullOrEmpty(phone) || string.IsNullOrEmpty(uniqueId)) return false;
            bool result = true;
            foreach (var validator in _phoneValidators)
            {
                if (!validator.Validate(phone))
                {
                    _logger.LogDebug($"phone:{phone} validate failed by {validator.GetType()}");
                    result = false;
                    break;
                }
            }
            if (!result) return result;

            foreach (var validator in _uniqueIdValidators)
            {
                if (!validator.Validate(uniqueId))
                {
                    _logger.LogDebug($"uniqueId:{uniqueId} validate failed by {validator.GetType()}");
                    result = false;
                    break;
                }
            }
            return result;
        }

        public void AfterSend(string phone, string uniqueId)
        {
            if (string.IsNullOrEmpty(phone) || string.IsNullOrEmpty(uniqueId)) return;
            foreach (var validator in _phoneValidators)
            {
                validator.Statistics(phone);
            }

            foreach (var validator in _uniqueIdValidators)
            {
                validator.Statistics(uniqueId);
            }
        }
    }
}
